from PIL import Image
import os
from tqdm import tqdm
import xml.etree.ElementTree as ET

# Set image-input path
folder_path = 'F:\\items\\bike-model\\搜集的数据集\\解压后\\archive(1)\\dataset\\JPEGImages'

# Set image-output path
output_folder_path = 'F:\\items\\bike-model\\搜集的数据集\\解压后\\archive(1)\\dataset\\zzxi'

# Set annotation-input path
annotation_input_path = 'F:\\items\\bike-model\\搜集的数据集\\解压后\\archive(1)\\dataset\\Annotations'

# Set annotation-output path
annotation_output_path = 'F:\\items\\bike-model\\搜集的数据集\\解压后\\archive(1)\\dataset\\zzxa'

# Set the desired image size
new_size = (640, 640)

for filename in tqdm(os.listdir(folder_path)):
    if filename.split('.')[-1] == 'jpg':
        file_path = os.path.join(folder_path, filename)
        # Load the image
        image = Image.open(file_path)

        # Get the original image size
        orig_width, orig_height = image.size

        # Resize the image using the LANCZOS resampling filter
        image = image.resize(new_size, Image.Resampling.LANCZOS)

        output_file_path = os.path.join(output_folder_path, filename)

        # Calculate the scale factors for width and height
        width_scale = new_size[0] / orig_width
        height_scale = new_size[1] / orig_height

        # Load the VOC XML file
        try:
            tree = ET.parse(os.path.join(annotation_input_path, filename.split('.')[0] + '.xml'))
            root = tree.getroot()

            # Save the resized image
            image.save(output_file_path)

            # Update the image size information
            size = root.find('size')
            size.find('width').text = str(new_size[0])
            size.find('height').text = str(new_size[1])

            # Update the annotation coordinates
            for obj in root.findall('object'):
                bbox = obj.find('bndbox')
                xmin = int(float(bbox.find('xmin').text) * width_scale)
                ymin = int(float(bbox.find('ymin').text) * height_scale)
                xmax = int(float(bbox.find('xmax').text) * width_scale)
                ymax = int(float(bbox.find('ymax').text) * height_scale)
                bbox.find('xmin').text = str(xmin)
                bbox.find('ymin').text = str(ymin)
                bbox.find('xmax').text = str(xmax)
                bbox.find('ymax').text = str(ymax)

            # Save the updated VOC XML file
            tree.write(os.path.join(annotation_output_path, filename.split('.')[0] + '.xml'))
        except FileNotFoundError:
            print(filename)
            os.remove(file_path)
